/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.examat.web.listeners;

import javax.enterprise.inject.spi.Bean;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.bean.ManagedProperty;
import javax.inject.Inject;
import org.examat.web.beans.ControlUsuariosBean;
import org.examat.web.controladores.util.Sesiones;

/**
 *
 * @author Fer
 */
public class LoginPhaseListener 
    implements PhaseListener
{
    
    @Override
    public void afterPhase(PhaseEvent event) 
    {
        FacesContext fc = event.getFacesContext();

        System.out.println("afterPhase()");
        // Check to see if they are on the login page.
        boolean loginPage = 
                fc.getViewRoot().getViewId().lastIndexOf("login") > -1;
        boolean registroPage =
                fc.getViewRoot().getViewId().lastIndexOf("registro") > -1;
              
        ControlUsuariosBean control = 
                (ControlUsuariosBean) fc.getApplication()
                .evaluateExpressionGet(fc, "#{controlUsuariosBean}", ControlUsuariosBean.class);
        if (!registroPage && !loginPage && !loggedIn(control)) {
            control.logout();
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            nh.handleNavigation(fc, null, "login");
        }
        else if(registroPage && loggedIn(control)) {
            NavigationHandler nh = fc.getApplication().getNavigationHandler();
            if(Sesiones.get("user_type").equals("alumno"))
                nh.handleNavigation(fc, null, "lobby");
            else if(Sesiones.get("user_type").equals("profesor"))
                nh.handleNavigation(fc, null, "consola");
        }
        
    }

    private boolean loggedIn(ControlUsuariosBean control) 
    {
        return control.estaLoggeado(Sesiones.get("user_claveunica").toString());
    }
    
    @Override
    public void beforePhase(PhaseEvent event) 
    {
    }

    @Override
    public PhaseId getPhaseId() 
    {
        return PhaseId.RESTORE_VIEW;
    }
}
